package main

import (
	"bufio"
	"flag"
	"fmt"
	"io"
	"os"
)

func main() {
	//written, err := copyTest("./src/17_file/doc/pic/picTest.png", "./src/17_file/doc/pic/picTestCopy.png")
	//fmt.Println(written, err)
	//wordCountStatistics("./src/17_file/doc/readTest2.txt")
	//cmdArgsTest()
	cmdArgsFlagTest()
}

func copyTest(src, dst string) (written int64, err error) {
	srcFile, err := os.Open(src)
	if err != nil {
		return 0, err
	}
	defer srcFile.Close()
	reader := bufio.NewReader(srcFile)
	dstFile, err := os.OpenFile(dst, os.O_WRONLY|os.O_CREATE, 0777)
	if err != nil {
		return 0, err
	}
	defer dstFile.Close()
	writer := bufio.NewWriter(dstFile)
	return io.Copy(writer, reader)
}

type CharCount struct {
	EnCount    int
	NumCount   int
	SpaceCount int
	OtherCount int
}

func (c CharCount) String() string {
	return fmt.Sprintf("enCount: %d, numCount: %d, spaceCount: %d, otherCount: %d", c.EnCount,
		c.NumCount, c.SpaceCount, c.OtherCount)
}

func wordCountStatistics(path string) {
	// 打开一个文件，创建一个Reader
	// 每读取一行，就去统计该行有多少个英文、数字、空格和其他字符
	// 然后将结果保存到一个结构体
	file, err := os.Open(path)
	if err != nil {
		fmt.Println("open file err:", file)
		return
	}
	defer file.Close()
	var charCount CharCount
	reader := bufio.NewReader(file)
	for {
		str, err := reader.ReadString('\n')
		for _, v := range str {
			switch {
			case v >= 'a' && v <= 'z':
				fallthrough
			case v >= 'A' && v <= 'Z':
				charCount.EnCount++
			case v == ' ':
				charCount.SpaceCount++
			case v >= '0' && v <= '9':
				charCount.NumCount++
			default:
				charCount.OtherCount++
			}
		}
		if err == io.EOF {
			break
		}
	}
	fmt.Println(charCount)
}

func cmdArgsTest() {
	fmt.Println("命令行的参数有", len(os.Args))
	// 遍历os.Args切片，就可以得到所有的命令行参数
	for i, v := range os.Args {
		fmt.Printf("args[%d] = %s\n", i, v)
	}
}

func cmdArgsFlagTest() {
	// 定义几个变量，用于接收命令行的参数
	var user string
	var pwd string
	var host string
	var port int
	flag.StringVar(&user, "u", "", "用户名，默认为空")
	flag.StringVar(&pwd, "pwd", "", "密码，默认为空")
	flag.StringVar(&host, "h", "localhost", "主机名，默认为空")
	flag.IntVar(&port, "port", 3306, "端口号，默认为3306")

	// 非常重要的操作，必须调用！！！！！！！
	flag.Parse()

	fmt.Printf("user: %s,\npwd: %s,\nhost:%s,\nport:%d,\n",
		user, pwd, host, port)
}
